﻿using Hjt212Parser;
using log4net;
using System;
using System.Data.Entity.Validation;
using System.Linq;
using DataProcessorDust.Properties;

namespace DataProcessorDust.EF
{
    public static class ProcessorData
    {
        private static ILog Log = LogManager.GetLogger(typeof(ProcessorData));
        /// <summary>
        /// 实时数据2011指令处理
        /// </summary>
        /// <param name="pCtx"></param>
        /// <param name="content"></param>
        public static void Process2011(LampblackMonitorEntities pCtx, string content)
        {
            try
            {
                var mn = Parser.GetStringByKey("MN", content);
                if (string.IsNullOrEmpty(mn))
                {
                    return;
                }
                var port = FacadeBufferInfoAndUtil.Port(mn);
                if (port == null)
                {
                    return;
                }
                var datatime = Parser.GetDateTimeByKey("DataTime", content);
                if (!datatime.HasValue)
                {
                    return;
                }
                RealDataMain mainRecord = new RealDataMain
                {
                    企业基本信息ID = port.企业基本信息ID,
                    监测设备ID = port.ID,
                    数据时间 = datatime.Value,
                    SD卡状态 = "正常",
                    联网状态 = "在线",
                    风机状态 = FacadeBufferInfoAndUtil.ConvertFanStatus(Parser.GetStringByKey(Settings.Default.FanFactor+"-Rtd", content)),
                    净化器状态 = FacadeBufferInfoAndUtil.ConvertPurifierStatus(Parser.GetIntByKey(Settings.Default.PurifierFactor + "-Rtd", content))
                };
                pCtx.RealDataMains.Add(mainRecord);

                var factors = Parser.GetPollutantCodes(content);
                factors.Remove(Settings.Default.FanFactor);
                factors.Remove(Settings.Default.PurifierFactor);

                foreach (var factor in factors)
                {
                    var factorCode = FacadeBufferInfoAndUtil.Factor(factor);
                    RealDataDetail sub = new RealDataDetail
                    {
                        污染物编码ID = factorCode.ID,
                        数据 = Parser.GetFloatByKey(factor + "-Rtd", content)
                    };
                    mainRecord.RealDataDetails.Add(sub);
                }
                pCtx.SaveChanges();
            }
            catch (DbEntityValidationException dbEx)
            {
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        Log.Error(string.Format("Class: {0}, Property: {1}, Error: {2}", validationErrors.Entry.Entity.GetType().FullName, validationError.PropertyName, validationError.ErrorMessage));
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex);
            }
        }

        /// <summary>
        /// 实时数据2011指令处理
        /// </summary>
        /// <param name="pCtx"></param>
        /// <param name="content"></param>
        public static void Process2011ForMonitor(LampblackMonitorEntities pCtx, string content)
        {
            try
            {
                var mn = Parser.GetStringByKey("MN", content);
                if (string.IsNullOrEmpty(mn))
                {
                    return;
                }
                var port = FacadeBufferInfoAndUtil.Port(mn);
                if (port == null)
                {
                    return;
                }
                var datatime = Parser.GetDateTimeByKey("DataTime", content);
                if (!datatime.HasValue)
                {
                    return;
                }

                RealDataMonitorMain mainRecord =
                    pCtx.RealDataMonitorMains.FirstOrDefault(t => t.企业基本信息ID == port.企业基本信息ID && t.监测设备ID == port.ID);


                if (mainRecord == null)
                {
                    mainRecord = new RealDataMonitorMain();
                    pCtx.RealDataMonitorMains.Add(mainRecord);

                }
                mainRecord.企业基本信息ID = port.企业基本信息ID;
                mainRecord.监测设备ID = port.ID;
                mainRecord.数据时间 = datatime.Value;
                mainRecord.SD卡状态 = "正常";
                mainRecord.联网状态 = "在线";
                mainRecord.风机状态 =
                    FacadeBufferInfoAndUtil.ConvertFanStatus(Parser.GetStringByKey(Settings.Default.FanFactor,
                        content));
                mainRecord.净化器状态 =
                    FacadeBufferInfoAndUtil.ConvertPurifierStatus(Parser.GetIntByKey(Settings.Default.PurifierFactor,
                        content));


                var factors = Parser.GetPollutantCodes(content);
                factors.Remove(Settings.Default.FanFactor);
                factors.Remove(Settings.Default.PurifierFactor);

                foreach (var factor in factors)
                {
                    var factorCode = FacadeBufferInfoAndUtil.Factor(factor);

                    var sub = mainRecord.RealDataMonitorDetails.FirstOrDefault(t => t.污染物编码ID == factorCode.ID);
                    if (sub == null)
                    {
                        sub = new RealDataMonitorDetail();
                        mainRecord.RealDataMonitorDetails.Add(sub);
                    }
                    sub.污染物编码ID = factorCode.ID;
                    sub.数据 = Parser.GetFloatByKey(factor + "-Rtd", content);
                }
                pCtx.SaveChanges();
            }
            catch (DbEntityValidationException dbEx)
            {
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        Log.Error(string.Format("Class: {0}, Property: {1}, Error: {2}", validationErrors.Entry.Entity.GetType().FullName, validationError.PropertyName, validationError.ErrorMessage));
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex);
            }

        }

        /// <summary>
        /// 数据2051指令处理
        /// </summary>
        /// <param name="pCtx"></param>
        /// <param name="content"></param>
        public static void Process2051(LampblackMonitorEntities pCtx, string content)
        {
            try
            {
                var mn = Parser.GetStringByKey("MN", content);
                if (string.IsNullOrEmpty(mn))
                {
                    return;
                }
                var port = FacadeBufferInfoAndUtil.Port(mn);
                if (port == null)
                {
                    return;
                }
                var datatime = Parser.GetDateTimeByKey("DataTime", content);
                if (!datatime.HasValue)
                {
                    return;
                }
                MinuteDataMain mainRecord = new MinuteDataMain
                {
                    企业基本信息ID = port.企业基本信息ID,
                    监测设备ID = port.ID,
                    数据时间 = datatime.Value,

                    风机状态 = FacadeBufferInfoAndUtil.ConvertFanStatus(Parser.GetStringByKey(Settings.Default.FanFactor+"-Avg", content)),
                    净化器状态 = FacadeBufferInfoAndUtil.ConvertPurifierStatus(Parser.GetIntByKey(Settings.Default.PurifierFactor + "-Avg", content))
                };
                pCtx.MinuteDataMains.Add(mainRecord);

                var factors = Parser.GetPollutantCodes(content);
                factors.Remove(Settings.Default.FanFactor);
                factors.Remove(Settings.Default.PurifierFactor);

                foreach (var factor in factors)
                {
                    var factorCode = FacadeBufferInfoAndUtil.Factor(factor);
                    MinuteDataDetail sub = new MinuteDataDetail
                    {
                        污染物编码ID = factorCode.ID,
                        数据 = Parser.GetFloatByKey(factor + "-Avg", content)
                    };
                    mainRecord.MinuteDataDetails.Add(sub);
                }
                pCtx.SaveChanges();
            }
            catch (DbEntityValidationException dbEx)
            {
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        Log.Error(string.Format("Class: {0}, Property: {1}, Error: {2}", validationErrors.Entry.Entity.GetType().FullName, validationError.PropertyName, validationError.ErrorMessage));
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex);
            }
        }

        /// <summary>
        /// 数据2061指令处理
        /// </summary>
        /// <param name="pCtx"></param>
        /// <param name="content"></param>
        public static void Process2061(LampblackMonitorEntities pCtx, string content)
        {
            try
            {
                var mn = Parser.GetStringByKey("MN", content);
                if (string.IsNullOrEmpty(mn))
                {
                    return;
                }
                var port = FacadeBufferInfoAndUtil.Port(mn);
                if (port == null)
                {
                    return;
                }
                var datatime = Parser.GetDateTimeByKey("DataTime", content);
                if (!datatime.HasValue)
                {
                    return;
                }
                var begin=new DateTime(datatime.Value.Year, datatime.Value.Month,datatime.Value.Day, datatime.Value.Hour, 0,0);
                var end = begin.AddHours(1);
                HourDataMain mainRecord = pCtx.HourDataMains
                    .Where(t => t.企业基本信息ID == port.企业基本信息ID && t.监测设备ID == port.ID)
                    .FirstOrDefault(t => t.数据时间 >= begin && t.数据时间 < end);

                if (mainRecord == null)
                {
                    mainRecord = new HourDataMain();
                    pCtx.HourDataMains.Add(mainRecord);
                }
                mainRecord.企业基本信息ID = port.企业基本信息ID;
                mainRecord.监测设备ID = port.ID;
                mainRecord.数据时间 = datatime.Value;
                mainRecord.风机状态 = FacadeBufferInfoAndUtil.ConvertFanStatus(Parser.GetStringByKey(Settings.Default.FanFactor + "-Avg", content));
                mainRecord.净化器状态 = FacadeBufferInfoAndUtil.ConvertPurifierStatus(Parser.GetIntByKey(Settings.Default.PurifierFactor + "-Avg", content));
                
                var factors = Parser.GetPollutantCodes(content);
                factors.Remove(Settings.Default.FanFactor);
                factors.Remove(Settings.Default.PurifierFactor);

                foreach (var factor in factors)
                {
                    var factorCode = FacadeBufferInfoAndUtil.Factor(factor);
                    HourDataDetail sub = mainRecord.HourDataDetails
                        .FirstOrDefault(t => t.污染物编码ID == factorCode.ID);
                    if (sub == null)
                    {
                        sub = new HourDataDetail();
                        mainRecord.HourDataDetails.Add(sub);
                    }
                    sub.污染物编码ID = factorCode.ID;
                    sub.数据 = Parser.GetFloatByKey(factor + "-Avg", content);
                }
                pCtx.SaveChanges();
            }
            catch (DbEntityValidationException dbEx)
            {
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        Log.Error(string.Format("Class: {0}, Property: {1}, Error: {2}", validationErrors.Entry.Entity.GetType().FullName, validationError.PropertyName, validationError.ErrorMessage));
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex);
            }
        }

        /// <summary>
        /// 数据2031指令处理
        /// </summary>
        /// <param name="pCtx"></param>
        /// <param name="content"></param>
        public static void Process2031(LampblackMonitorEntities pCtx, string content)
        {
            try
            {
                var mn = Parser.GetStringByKey("MN", content);
                if (string.IsNullOrEmpty(mn))
                {
                    return;
                }
                var port = FacadeBufferInfoAndUtil.Port(mn);
                if (port == null)
                {
                    return;
                }
                var datatime = Parser.GetDateTimeByKey("DataTime", content);
                if (!datatime.HasValue)
                {
                    return;
                }
                var begin = new DateTime(datatime.Value.Year, datatime.Value.Month, datatime.Value.Day, 0,0, 0);
                var end = begin.AddDays(1);
                DayDataMain mainRecord = pCtx.DayDataMains
                    .Where(t => t.企业基本信息ID == port.企业基本信息ID && t.监测设备ID == port.ID)
                    .FirstOrDefault(t => t.数据时间 >= begin && t.数据时间 < end);

                if (mainRecord == null)
                {
                    mainRecord = new DayDataMain();
                    pCtx.DayDataMains.Add(mainRecord);
                }
                mainRecord.企业基本信息ID = port.企业基本信息ID;
                mainRecord.监测设备ID = port.ID;
                mainRecord.数据时间 = datatime.Value;
                mainRecord.风机状态 = FacadeBufferInfoAndUtil.ConvertFanStatus(Parser.GetStringByKey(Settings.Default.FanFactor + "-Avg", content));
                mainRecord.净化器状态 = FacadeBufferInfoAndUtil.ConvertPurifierStatus(Parser.GetIntByKey(Settings.Default.PurifierFactor + "-Avg", content));

                var factors = Parser.GetPollutantCodes(content);
                factors.Remove(Settings.Default.FanFactor);
                factors.Remove(Settings.Default.PurifierFactor);

                foreach (var factor in factors)
                {
                    var factorCode = FacadeBufferInfoAndUtil.Factor(factor);
                    DayDataDetail sub = mainRecord.DayDataDetails
                        .FirstOrDefault(t => t.污染物编码ID == factorCode.ID);
                    if (sub == null)
                    {
                        sub = new DayDataDetail();
                        mainRecord.DayDataDetails.Add(sub);
                    }
                    sub.污染物编码ID = factorCode.ID;
                    sub.数据 = Parser.GetFloatByKey(factor + "-Avg", content);
                }
                pCtx.SaveChanges();
            }
            catch (DbEntityValidationException dbEx)
            {
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        Log.Error(string.Format("Class: {0}, Property: {1}, Error: {2}", validationErrors.Entry.Entity.GetType().FullName, validationError.PropertyName, validationError.ErrorMessage));
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex);
            }
        }
        public static void Process2031ToMonth(LampblackMonitorEntities pCtx, string content)
        {
            try
            {
                var mn = Parser.GetStringByKey("MN", content);
                if (string.IsNullOrEmpty(mn))
                {
                    return;
                }
                var port = FacadeBufferInfoAndUtil.Port(mn);
                if (port == null)
                {
                    return;
                }
                var datatime = Parser.GetDateTimeByKey("DataTime", content);
                if (!datatime.HasValue)
                {
                    return;
                }
                var begin = new DateTime(datatime.Value.Year, datatime.Value.Month, 1, 0, 0, 0);
                var end = begin.AddMonths(1);
                MonthDataMain mainRecord = pCtx.MonthDataMains
                    .Where(t => t.企业基本信息ID == port.企业基本信息ID && t.监测设备ID == port.ID)
                    .FirstOrDefault(t => t.数据时间 >= begin && t.数据时间 < end);

                if (mainRecord == null)
                {
                    mainRecord = new MonthDataMain();
                    pCtx.MonthDataMains.Add(mainRecord);
                }
                mainRecord.企业基本信息ID = port.企业基本信息ID;
                mainRecord.监测设备ID = port.ID;
                mainRecord.数据时间 = datatime.Value;
                mainRecord.风机状态 = FacadeBufferInfoAndUtil.ConvertFanStatus(Parser.GetStringByKey(Settings.Default.FanFactor + "-Avg", content));
                mainRecord.净化器状态 = FacadeBufferInfoAndUtil.ConvertPurifierStatus(Parser.GetIntByKey(Settings.Default.PurifierFactor + "-Avg", content));

                var factors = Parser.GetPollutantCodes(content);
                factors.Remove(Settings.Default.FanFactor);
                factors.Remove(Settings.Default.PurifierFactor);

                foreach (var factor in factors)
                {
                    var factorCode = FacadeBufferInfoAndUtil.Factor(factor);
                    MonthDataDetail sub = mainRecord.MonthDataDetails
                        .FirstOrDefault(t => t.污染物编码ID == factorCode.ID);
                    if (sub == null)
                    {
                        sub = new MonthDataDetail();
                        mainRecord.MonthDataDetails.Add(sub);
                    }
                    sub.污染物编码ID = factorCode.ID;
                    var dayIds= pCtx.DayDataMains
                        .Where(t => t.企业基本信息ID == port.企业基本信息ID && t.监测设备ID == port.ID)
                        .Where(t => t.数据时间 >= begin && t.数据时间 < end).Select(t=>t.ID).ToList();
                    var monthAvg = pCtx.DayDataDetails.Where(t => dayIds.Contains(t.主日ID)).Average(t => t.数据);
                    sub.数据 = monthAvg;// Parser.GetFloatByKey(factor + "-Avg", content);
                }
                pCtx.SaveChanges();
            }
            catch (DbEntityValidationException dbEx)
            {
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        Log.Error(string.Format("Class: {0}, Property: {1}, Error: {2}", validationErrors.Entry.Entity.GetType().FullName, validationError.PropertyName, validationError.ErrorMessage));
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex);
            }
        }

        public static void Process2031ToYear(LampblackMonitorEntities pCtx, string content)
        {
            try
            {
                var mn = Parser.GetStringByKey("MN", content);
                if (string.IsNullOrEmpty(mn))
                {
                    return;
                }
                var port = FacadeBufferInfoAndUtil.Port(mn);
                if (port == null)
                {
                    return;
                }
                var datatime = Parser.GetDateTimeByKey("DataTime", content);
                if (!datatime.HasValue)
                {
                    return;
                }
                var begin = new DateTime(datatime.Value.Year, 1, 1, 0, 0, 0);
                var end = begin.AddYears(1);
                YearDataMain mainRecord = pCtx.YearDataMains
                    .Where(t => t.企业基本信息ID == port.企业基本信息ID && t.监测设备ID == port.ID)
                    .FirstOrDefault(t => t.数据时间 >= begin && t.数据时间 < end);

                if (mainRecord == null)
                {
                    mainRecord = new YearDataMain();
                    pCtx.YearDataMains.Add(mainRecord);
                }
                mainRecord.企业基本信息ID = port.企业基本信息ID;
                mainRecord.监测设备ID = port.ID;
                mainRecord.数据时间 = datatime.Value;
                mainRecord.风机状态 = FacadeBufferInfoAndUtil.ConvertFanStatus(Parser.GetStringByKey(Settings.Default.FanFactor + "-Avg", content));
                mainRecord.净化器状态 = FacadeBufferInfoAndUtil.ConvertPurifierStatus(Parser.GetIntByKey(Settings.Default.PurifierFactor + "-Avg", content));

                var factors = Parser.GetPollutantCodes(content);
                factors.Remove(Settings.Default.FanFactor);
                factors.Remove(Settings.Default.PurifierFactor);

                foreach (var factor in factors)
                {
                    var factorCode = FacadeBufferInfoAndUtil.Factor(factor);
                    YearDataDetail sub = mainRecord.YearDataDetails
                        .FirstOrDefault(t => t.污染物编码ID == factorCode.ID);
                    if (sub == null)
                    {
                        sub = new YearDataDetail();
                        mainRecord.YearDataDetails.Add(sub);
                    }
                    sub.污染物编码ID = factorCode.ID;
                    var dayIds = pCtx.DayDataMains
                        .Where(t => t.企业基本信息ID == port.企业基本信息ID && t.监测设备ID == port.ID)
                        .Where(t => t.数据时间 >= begin && t.数据时间 < end).Select(t => t.ID).ToList();
                    var monthAvg = pCtx.DayDataDetails.Where(t => dayIds.Contains(t.主日ID)).Average(t => t.数据);
                    sub.数据 = monthAvg;// Parser.GetFloatByKey(factor + "-Avg", content);
                }
                pCtx.SaveChanges();
            }
            catch (DbEntityValidationException dbEx)
            {
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        Log.Error(string.Format("Class: {0}, Property: {1}, Error: {2}", validationErrors.Entry.Entity.GetType().FullName, validationError.PropertyName, validationError.ErrorMessage));
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex);
            }
        }

    }
}
